#include <iostream>
using namespace std;
#include <cstring>
#include <cassert>
class String // 自定义字符串类
{
public:
  String();                // 默认构造函数
  String(const char *src); // 带参数的构造函数
  ~String();               // 析构函数
  const char *ToString() const { return str; }
  unsigned int Length() const { return len; }
  String &operator=(const String &right);
  // 赋值运算符重载函数
private:
  char *str;
  unsigned int len; // 存放字符串的长度
};
String::String() // 默认构造函数
{
  len = 0;
  str = new char[len + 1];
  str[0] = '\0';
}
String::String(const char *src) // 带参数的构造函数
{
  len = strlen(src);
  str = new char[len + 1];
  if (!str)
  {
    cerr << "Allocation Error!\n";
    exit(1);
  }
  strcpy(str, src);
}
String::~String() // 析构函数
{
  delete str;
  str = NULL;
}
String &String::operator=(const String &right)
// 赋值运算符重载函数
{
  if (&right != this)
  {
    int length = right.Length();
    if (len < length)
    {
      delete[] str;
      str = new char[length + 1];
      assert(str != 0);
    }
    int i;
    for (i = 0; right.str[i] != '\0'; i++)
      str[i] = right.str[i];
    str[i] = '\0';
    len = length;
  }
  return *this;
}
int main()
{
  String str1("Hi!"), str2("Hello!");
  cout << "str1: " << str1.ToString() << endl;
  cout << "str2: " << str2.ToString() << endl;
  str1 = str2;
  cout << "str1: " << str1.ToString() << endl;
  return 0;
}
